package com.google.code.drift.dialog;

import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Message;

import com.google.code.drift.R;
import com.google.code.drift.api.AppSkyApp;
import com.google.code.drift.utils.DLog;
import com.google.code.drift.utils.JsonFactory;
import com.google.code.drift.utils.CommonUtils;

public class ChooseCityDialog extends AlertDialog.Builder {

	private String[] cityLocations = null;

	private AppSkyApp app = null;

	private Context context = null;

	boolean isItemChanged = false;

	public ChooseCityDialog(final Context context) {
		super(context);

		this.context = context;
		cityLocations = context.getResources().getStringArray(
				R.array.city_lat_lon);
		app = (AppSkyApp) ((Activity) context).getApplication();

		setIcon(R.drawable.ic_going_to);
		setTitle(R.string.choose_city);

		setSingleChoiceItems(R.array.city_names, 0, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				isItemChanged = true;
				int[] latitudeAndLongitude = makeLatitudeAndLongitude(cityLocations[which]);
				app.getMyInfo().setLocation(latitudeAndLongitude[0],
						latitudeAndLongitude[1]);
				app.setLocationChange();
			}

		});

		setPositiveButton(R.string.ok, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (!isItemChanged) {// 默认选择上海，如果用户没改变就点确定了，那要改变一下位置
					int[] latitudeAndLongitude = makeLatitudeAndLongitude(cityLocations[0]);
					app.getMyInfo().setLocation(latitudeAndLongitude[0],
							latitudeAndLongitude[1]);
					app.setLocationChange();
				}
				showProgress();
				sendChangeLocationJson();
			}
		});

		setNegativeButton(R.string.cancel, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});

	}

	private int[] makeLatitudeAndLongitude(String string) {
		String[] temp = string.split(",");
		int[] result = stringArrayConvertToIntArray(temp);
		result = incrementLatitudeAndLongitude(result);
		return result;
	}

	/**
	 * 生成300000以内的随机正负整数，然后与经纬度相加，为了防止多人覆盖同一个点
	 * 
	 * @param original
	 * @return
	 */
	private int[] incrementLatitudeAndLongitude(int[] original) {
		int[] result = original;
		Random i = new Random();
		int latIncrement = (int) (i.nextDouble() * 300000);
		int lonIncrement = (int) (i.nextDouble() * 300000);
		if (i.nextBoolean()) {
			latIncrement = -latIncrement;
		}
		if (i.nextBoolean()) {
			lonIncrement = -lonIncrement;
		}
		result[0] += latIncrement;
		result[1] += lonIncrement;
		return result;
	}

	/**
	 * 转换字符串数组
	 * 
	 * @param stringArray
	 * @return
	 */
	private int[] stringArrayConvertToIntArray(String[] stringArray) {
		int[] result = new int[stringArray.length];
		for (int n = 0; n < stringArray.length; n++) {
			result[n] = Integer.valueOf(stringArray[n]);
		}
		return result;
	}

	private void showProgress() {
		Message msg = new Message();
		Bundle bundle = new Bundle();
		bundle.putString("showMessage", "正在更改位置..");
		msg.setData(bundle);
		msg.what = CommonUtils.START_PROGRESS;
		app.sendMessageToHandler(msg);
	}

	private void sendChangeLocationJson() {
		JsonFactory jsonFactory = JsonFactory.getFactory();
		CommonUtils.sendDataToServerForTimeout(context, jsonFactory.makeUserChangeLocationJson(app.getMyInfo()
				.getUserId(), app.getMyInfo().getLatitude(), app.getMyInfo()
				.getLongitude()).toJSONString(), 30 * 1000);
	}

	private String returnChangeLocationJsonString() {
		AppSkyApp app = (AppSkyApp) context.getApplicationContext();
		JsonFactory jsonFactory = JsonFactory.getFactory();

		String loginJson = jsonFactory.makeUserChangeLocationJson(
				app.getMyInfo().getUserId(), app.getMyInfo().getLatitude(),
				app.getMyInfo().getLongitude()).toJSONString();

		return loginJson;
	}

}
